<!DOCTYPE html>



  


<html class="theme-next muse use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="本文主要分析一下NettyServer，HeaderExchangeServer实现细节。 1、NettyServer NettyServer整个类图如下： 首先从全貌上大概看一下NettyServer对象所持有的属性：">
<meta property="og:type" content="article">
<meta property="og:title" content="源码分析Dubbo网络通信篇NettyServer、HeaderExchangeServer">
<meta property="og:url" content="https://www.codingw.net/posts/5b5952d6.html">
<meta property="og:site_name" content="中间件兴趣圈">
<meta property="og:description" content="本文主要分析一下NettyServer，HeaderExchangeServer实现细节。 1、NettyServer NettyServer整个类图如下： 首先从全貌上大概看一下NettyServer对象所持有的属性：">
<meta property="og:locale">
<meta property="og:image" content="https://img-blog.csdn.net/20180723120806159?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="og:image" content="https://img-blog.csdn.net/20180723122046649?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">
<meta property="article:published_time" content="2020-11-26T09:33:01.000Z">
<meta property="article:modified_time" content="2021-04-26T12:10:24.415Z">
<meta property="article:author" content="中间件兴趣圈">
<meta property="article:tag" content="中间件">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://img-blog.csdn.net/20180723120806159?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '',
    scheme: 'Muse',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://www.codingw.net/posts/5b5952d6.html"/>





  <title>源码分析Dubbo网络通信篇NettyServer、HeaderExchangeServer | 中间件兴趣圈</title>
  








<meta name="generator" content="Hexo 5.4.0"></head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">中间件兴趣圈</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle">微信搜『中间件兴趣圈』，回复『Java』获取200本优质电子书</p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-question-circle"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://www.codingw.net/posts/5b5952d6.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/images/avatar.gif">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="中间件兴趣圈">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">源码分析Dubbo网络通信篇NettyServer、HeaderExchangeServer</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2020-11-26T17:33:01+08:00">
                2020-11-26
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/dubbo/" itemprop="url" rel="index">
                    <span itemprop="name">dubbo</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
          

          
          
             <span id="/posts/5b5952d6.html" class="leancloud_visitors" data-flag-title="源码分析Dubbo网络通信篇NettyServer、HeaderExchangeServer">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv"><i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv" ></span>次
            </span>
          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <div id="vip-container"><p> 本文主要分析一下NettyServer，HeaderExchangeServer实现细节。</p>
<h2 id="1、NettyServer"><a href="#1、NettyServer" class="headerlink" title="1、NettyServer"></a>1、NettyServer</h2><p> NettyServer整个类图如下：<br><img src="https://img-blog.csdn.net/20180723120806159?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br> 首先从全貌上大概看一下NettyServer对象所持有的属性：</p>
<span id="more"></span>

<ul>
<li>AbstractPeer<br>1、private final ChannelHandler handler ： 事件处理Handler。<br>2、private volatile URL url ：该协议的第一个服务提供者的URL，<br>Server只需要用到URL中的参数，与具体某一个服务没什么关系。</li>
<li>AbstractEndpoint<br>这些属性都是以第一个加载到的服务提供者的配置，不科学？超时机制需要后续关注】<br>1、private Codec2 codec ：编码解码器。<br>2、private int timeout ：      超时时间<br>3、private int connectTimeout ：连接超时时间<br>注，如果通过dubbo:provider改变codec,不同的服务提供者引用的默<br>认服务提供者参数不同，那这个只能是以第一个为主了，应该不科学？</li>
<li>AbstractServer<br>1、private InetSocketAddress localAddress ：url host:port地址。<br>2、private InetSocketAddress bindAddress：如果是多网卡，并且指定了 bind.ip、bind.port，如果为空，与localAddress相同。<br>3、private int accepts ： AbstractServer#accepts未使用到。<br>4、private int idleTimeout = 600;  AbstractServer#accepts未使用到。</li>
<li>NettyServer<br>1、private Map&lt; String, Channel&gt; channels：&lt; ip:port, channel&gt; 所有通道。<br>2、private ServerBootstrap bootstrap ： netty 服务端启动器。<br>3、private io.netty.channel.Channel channel：服务端监听通道。<br>4、private EventLoopGroup bossGroup;Netty boss线程组（负责连接事件）<br>5、private EventLoopGroup workerGroup ： nety work线程组（负责IO事件）<br>上述只是简单介绍一下Server端的属性，有如下几个疑问需要关注。<br>AbstractEndpoint中定义的属性，为什么可以取第一个服务提供者的配置。<br>AbstractServer中的accepts、idleTimeout为什么是取最后一服务提供者的配置【从代码中看，这两个属性，未使用】。</li>
</ul>
<h3 id="1-1-NettyServer-构造方法"><a href="#1-1-NettyServer-构造方法" class="headerlink" title="1.1 NettyServer 构造方法"></a>1.1 NettyServer 构造方法</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">public NettyServer(URL url, ChannelHandler handler) throws RemotingException &#123;</span><br><span class="line">        super(url, ChannelHandlers.wrap(handler, ExecutorUtil.setThreadName(url, SERVER_THREAD_POOL_NAME)));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>直接调用父类的public AbstractServer(URL url, ChannelHandler handler)方法，从前面的文章中得知， ChannelHandlers.wrap方法会对ChannelHandler handler进行封装，主要是加入事件分发模式(Dispatch)。</p>
<h4 id="1-1-1-AbstractServer构造方法"><a href="#1-1-1-AbstractServer构造方法" class="headerlink" title="1.1.1 AbstractServer构造方法"></a>1.1.1 AbstractServer构造方法</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public AbstractServer(URL url, ChannelHandler handler) throws RemotingException &#123;</span><br><span class="line">        super(url, handler);       &#x2F;&#x2F; @1</span><br><span class="line">        localAddress &#x3D; getUrl().toInetSocketAddress();   &#x2F;&#x2F; @2</span><br><span class="line"></span><br><span class="line">        String bindIp &#x3D; getUrl().getParameter(Constants.BIND_IP_KEY, getUrl().getHost());</span><br><span class="line">        int bindPort &#x3D; getUrl().getParameter(Constants.BIND_PORT_KEY, getUrl().getPort());</span><br><span class="line">        if (url.getParameter(Constants.ANYHOST_KEY, false) || NetUtils.isInvalidLocalHost(bindIp)) &#123;</span><br><span class="line">            bindIp &#x3D; NetUtils.ANYHOST;</span><br><span class="line">        &#125;</span><br><span class="line">        bindAddress &#x3D; new InetSocketAddress(bindIp, bindPort);   &#x2F;&#x2F; @3</span><br><span class="line">        this.accepts &#x3D; url.getParameter(Constants.ACCEPTS_KEY, Constants.DEFAULT_ACCEPTS);  </span><br><span class="line">        this.idleTimeout &#x3D; url.getParameter(Constants.IDLE_TIMEOUT_KEY, Constants.DEFAULT_IDLE_TIMEOUT); &#x2F;&#x2F; @4</span><br><span class="line">        try &#123;</span><br><span class="line">            doOpen();   &#x2F;&#x2F; @5</span><br><span class="line">            if (logger.isInfoEnabled()) &#123;</span><br><span class="line">                logger.info(&quot;Start &quot; + getClass().getSimpleName() + &quot; bind &quot; + getBindAddress() + &quot;, export &quot; + getLocalAddress());</span><br><span class="line">            &#125;</span><br><span class="line">        &#125; catch (Throwable t) &#123;</span><br><span class="line">            throw new RemotingException(url.toInetSocketAddress(), null, &quot;Failed to bind &quot; + getClass().getSimpleName()</span><br><span class="line">                    + &quot; on &quot; + getLocalAddress() + &quot;, cause: &quot; + t.getMessage(), t);</span><br><span class="line">        &#125;</span><br><span class="line">        &#x2F;&#x2F;fixme replace this with better method</span><br><span class="line">        DataStore dataStore &#x3D; ExtensionLoader.getExtensionLoader(DataStore.class).getDefaultExtension();</span><br><span class="line">        executor &#x3D; (ExecutorService) dataStore.get(Constants.EXECUTOR_SERVICE_COMPONENT_KEY, Integer.toString(url.getPort()));</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：调用父类的构造方法，主要初始化AbstractPeer（channelHandler、url）和AbstractEndpoint（codec2、timeout、idleTimeout ）<br>代码@2：根据URL中的host与端口，创建localAddress。<br>代码@3：如果配置了&lt; dubbo:parameter key = “bind.ip” value = “”/&gt; 与 &lt; dubbo:parameter key = “bind.port” /&gt;，则用该IP与端口创建bindAddress，通常用于多网卡，如果未配置，bindAddress与 localAddress绑定的IP与端口一样。<br>代码@4：初始化accepts与idleTimeout ,这两个参数未被其他地方使用。<br>代码@5，调用doOpen方法，正式在相应端口建立网络监听。</p>
<h3 id="1-2、源码分析NettyServer-doOpen"><a href="#1-2、源码分析NettyServer-doOpen" class="headerlink" title="1.2、源码分析NettyServer#doOpen"></a>1.2、源码分析NettyServer#doOpen</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">protected void doOpen() throws Throwable &#123;</span><br><span class="line">        NettyHelper.setNettyLoggerFactory();</span><br><span class="line">        bootstrap &#x3D; new ServerBootstrap();       &#x2F;&#x2F; @1</span><br><span class="line">        bossGroup &#x3D; new NioEventLoopGroup(1, new DefaultThreadFactory(&quot;NettyServerBoss&quot;, true));    &#x2F;&#x2F; @2</span><br><span class="line">        workerGroup &#x3D; new NioEventLoopGroup(getUrl().getPositiveParameter(Constants.IO_THREADS_KEY, Constants.DEFAULT_IO_THREADS),</span><br><span class="line">                new DefaultThreadFactory(&quot;NettyServerWorker&quot;, true));    &#x2F;&#x2F; @3</span><br><span class="line">        final NettyServerHandler nettyServerHandler &#x3D; new NettyServerHandler(getUrl(), this);   &#x2F;&#x2F; @4</span><br><span class="line">        channels &#x3D; nettyServerHandler.getChannels();</span><br><span class="line">        bootstrap.group(bossGroup, workerGroup)                                                                        &#x2F;&#x2F; @5</span><br><span class="line">                .channel(NioServerSocketChannel.class)</span><br><span class="line">                .childOption(ChannelOption.TCP_NODELAY, Boolean.TRUE)</span><br><span class="line">                .childOption(ChannelOption.SO_REUSEADDR, Boolean.TRUE)</span><br><span class="line">                .childOption(ChannelOption.ALLOCATOR, PooledByteBufAllocator.DEFAULT)</span><br><span class="line">                .childHandler(new ChannelInitializer&lt;NioSocketChannel&gt;() &#123;</span><br><span class="line">                    @Override</span><br><span class="line">                    protected void initChannel(NioSocketChannel ch) throws Exception &#123;</span><br><span class="line">                        NettyCodecAdapter adapter &#x3D; new NettyCodecAdapter(getCodec(), getUrl(), NettyServer.this);</span><br><span class="line">                        ch.pipeline()&#x2F;&#x2F;.addLast(&quot;logging&quot;,new LoggingHandler(LogLevel.INFO))&#x2F;&#x2F;for debug                       </span><br><span class="line">                                .addLast(&quot;decoder&quot;, adapter.getDecoder())   </span><br><span class="line">                                .addLast(&quot;encoder&quot;, adapter.getEncoder())</span><br><span class="line">                                .addLast(&quot;handler&quot;, nettyServerHandler);</span><br><span class="line">                    &#125;</span><br><span class="line">                &#125;);</span><br><span class="line">        &#x2F;&#x2F; bind</span><br><span class="line">        ChannelFuture channelFuture &#x3D; bootstrap.bind(getBindAddress());     &#x2F;&#x2F; @6</span><br><span class="line">        channelFuture.syncUninterruptibly();</span><br><span class="line">        channel &#x3D; channelFuture.channel();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>代码@1：创建Netty服务端启动帮助类ServerBootstrap.<br>代码@2：创建服务端Boss线程，线程名：.NettyServerBoss，主要负责客户端的连接事件，主从多Reactor线程模型中的主线程（连接事件）。<br>代码@3：创建服务端Work线程组，线程名：NettyServerWorker-序号，线程个数取自参数：iothreads，默认为(CPU核数+1)与32取小值，顾名思义，IO线程数，主要处理读写事件，编码、解码都在IO线程中完成。<br>代码@4：创建用户Handler,这里是NettyServerHandler。<br>代码@5：Netty启动的常规写法，关注如下内容：<br>addLast(“decoder”, adapter.getDecoder())  : 添加解码器<br>addLast(“encoder”, adapter.getEncoder()) ：添加编码器<br>addLast(“handler”, nettyServerHandler) ：添加业务Handler。</p>
<p>这里简单介绍一下流程：<br>1、客户端建立与服务端连接，此时Boss线程的连接事件触发，建立TCP连接，并向IO线程注册该通道(Channel0)的读事件。<br>2、当客户端向服务端发送请求消息后，IO线程中的读事件触发，会首先调用adapter.getDecoder() 根据对应的请求协议（例如dubbo）从二进制流中解码出一个完整的请求对象，然后传入到业务handler,例如nettyServerHandler，执行相应的事件方法，例如recive方法。<br>3、当服务端向Channel写入响应结果时，首先编码器会按照协议编码成二进制流，供客户端解码。、<br>如果对Netty想深入学习的话，请移步到作者的《源码分析Netty系列》<a target="_blank" rel="noopener" href="https://blog.csdn.net/prestigeding/article/details/53977445">https://blog.csdn.net/prestigeding/article/details/53977445</a></p>
<h2 id="2、HeaderExchangeServer"><a href="#2、HeaderExchangeServer" class="headerlink" title="2、HeaderExchangeServer"></a>2、HeaderExchangeServer</h2><p>根据Dubbo服务端初始化流程，我们可知，Dubbo为了封装各种不同的网络实现客户端（netty、mina）等，映入了Exchangers层，通用存在ExchangeServer，其实现Server并内部持有具体的Server实现端，例如NettyServer。<br><img src="https://img-blog.csdn.net/20180723122046649?watermark/2/text/aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3ByZXN0aWdlZGluZw==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70" alt="这里写图片描述"><br>接下来，我们重点来关注一下HeaderExchangeServer.<br>核心属性如下：</p>
<ul>
<li>ScheduledExecutorService scheduled：心跳线程数，线程名称前缀，dubbo-remoting-server-heartbeat-thread-序号</li>
<li>private final Server server：具体的Server实现类，例如NettyServer。</li>
<li>private ScheduledFuture&lt; ?&gt; heartbeatTimer：心跳调度Future，可以通过future取消心跳等动作。</li>
<li>private int heartbeat：心跳间隔时间</li>
<li>private int heartbeatTimeout：心跳超时时间，至少为heartbeat的两倍</li>
</ul>
<h3 id="2-1-构造函数"><a href="#2-1-构造函数" class="headerlink" title="2.1 构造函数"></a>2.1 构造函数</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">public HeaderExchangeServer(Server server) &#123;</span><br><span class="line">        if (server &#x3D;&#x3D; null) &#123;</span><br><span class="line">            throw new IllegalArgumentException(&quot;server &#x3D;&#x3D; null&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        this.server &#x3D; server;</span><br><span class="line">        this.heartbeat &#x3D; server.getUrl().getParameter(Constants.HEARTBEAT_KEY, 0);</span><br><span class="line">        this.heartbeatTimeout &#x3D; server.getUrl().getParameter(Constants.HEARTBEAT_TIMEOUT_KEY, heartbeat * 3);</span><br><span class="line">        if (heartbeatTimeout &lt; heartbeat * 2) &#123;</span><br><span class="line">            throw new IllegalStateException(&quot;heartbeatTimeout &lt; heartbeatInterval * 2&quot;);</span><br><span class="line">        &#125;</span><br><span class="line">        startHeartbeatTimer();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>说明，主要是通过heartbeat参数设置心跳间隔，如果不配置，则不启动心跳检测。从上面看来HeaderExchangeServer内部持有Server,并封装了心跳的功能，在这里就不细细分析了。</p>
</div>

			<script src="https://my.openwrite.cn/js/readmore.js" type="text/javascript"></script>
			<script>
			var isMobile = navigator.userAgent.match(/(phone|pad|pod|iPhone|iPod|ios|iPad|Android|Mobile|BlackBerry|IEMobile|MQQBrowser|JUC|Fennec|wOSBrowser|BrowserNG|WebOS|Symbian|Windows Phone)/i);
			if (!isMobile) {
			    var btw = new BTWPlugin();
			    btw.init({
			        "id": "vip-container",
			        "blogId": "18019-1573088808868-542",
			        "name": "中间件兴趣圈",
			        "qrcode": "https://img-blog.csdnimg.cn/20190314214003962.jpg",
			        "keyword": "more"
			    });
			}
			</script>
		
      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/posts/531bec0b.html" rel="next" title="源码分析Dubbo网络通讯篇概要总结(类图一览、服务端、客户端网络构造流程一览)">
                <i class="fa fa-chevron-left"></i> 源码分析Dubbo网络通讯篇概要总结(类图一览、服务端、客户端网络构造流程一览)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/posts/4fb5ca23.html" rel="prev" title="源码分析Dubbo监控中心实现原理">
                源码分析Dubbo监控中心实现原理 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <p class="site-author-name" itemprop="name"></p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">139</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">18</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#1%E3%80%81NettyServer"><span class="nav-number">1.</span> <span class="nav-text">1、NettyServer</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-NettyServer-%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="nav-number">1.1.</span> <span class="nav-text">1.1 NettyServer 构造方法</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-1-AbstractServer%E6%9E%84%E9%80%A0%E6%96%B9%E6%B3%95"><span class="nav-number">1.1.1.</span> <span class="nav-text">1.1.1 AbstractServer构造方法</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2%E3%80%81%E6%BA%90%E7%A0%81%E5%88%86%E6%9E%90NettyServer-doOpen"><span class="nav-number">1.2.</span> <span class="nav-text">1.2、源码分析NettyServer#doOpen</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2%E3%80%81HeaderExchangeServer"><span class="nav-number">2.</span> <span class="nav-text">2、HeaderExchangeServer</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-number">2.1.</span> <span class="nav-text">2.1 构造函数</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">中间件兴趣圈</span>

  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Muse</a> v5.1.4</div>




        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      
    </span>
  

  
    <span class="site-pv">
      <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("NNEhOL0iOcflg8f1U3HUqiCq-gzGzoHsz", "7kSmkbbb3DktmHALlShDsBUF");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  

  
  

  

  

  

</body>
</html>
